package com.bella.api.filter;

import com.alibaba.fastjson.JSON;
import com.bella.api.system.dto.AdminDto;
import com.bella.api.system.service.UserService;
import com.bella.api.utils.AdminContext;
import com.bella.api.utils.ApiResponse;
import com.bella.api.utils.ApiResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zsq
 * @create 2020-05-12-11:03
 */
public class AuthWebInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthWebInterceptor.class);

    @Autowired
    UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object args) throws Exception {
        String token = request.getHeader("Authentication-Admin-Web-Token");

        // token换取用户信息
        if (StringUtils.isNotBlank(token)) {
            AdminDto admin = null;
            try {
                admin = userService.getAdminByToken(token);
            } catch (Exception e) {
                logger.info("获取token对象失败" + e);
            }
            if (admin != null) {
                AdminContext.set(admin);
            } else {
                ApiResponse<?> error = new ApiResponse<>(ApiResponseCode.invalid_access_token);
                returnJson(response, JSON.toJSONString(error));
                return false;
            }
        } else {
            ApiResponse<?> error = new ApiResponse<>(ApiResponseCode.invalid_access_token);
            returnJson(response, JSON.toJSONString(error));
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            logger.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
